//
//  CZOAuthViewController.swift
//  CZVVeiBo
//
//  Created by smile on 2017/7/30.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit
import YYModel
class CZOAuthViewController: UIViewController {
    
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        setupNav()
    }
    
    // MARK: - 设置导航
    fileprivate func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imgName: nil, target: self, action: #selector(autofillClick))
        navigationItem.title = "微博登录"
    }
    
    // MARK: - 懒加载控件
    fileprivate lazy var webView: UIWebView = {
        let webView = UIWebView()
        // 设置代理
        webView.delegate = self
        // 需要加载的url的地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(CZAppKey)&redirect_uri=\(CZRedirect_uri)"
//        if let url = URL(string: urlString) {
//            let request = URLRequest(url: url)
//            // 加载request
//            webView.loadRequest(request)
//        }
        // 代码前后移动command+[ 左移动  command+] 右移动
        guard let url =  URL(string: urlString) else{
            return webView
        }
        let request = URLRequest(url: url)
        // 加载request
        webView.loadRequest(request)
        return webView
    }()
}
// MARK: - 监听事件
extension CZOAuthViewController{
    // 取消
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    // 自动填充
    @objc fileprivate func autofillClick(){
        // js注入代码
        let jsString = "document.getElementById('userId').value='\(CZWeiboName)',document.getElementById('passwd').value='\(CZWeiboPasswd)'"
        webView.stringByEvaluatingJavaScript(from: jsString)

    }
}
// MARK: - UIWebViewDelegate
extension CZOAuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
    }
    // 监听webView将要加载的请求 -> 返回值是否加载这个请求
    // 默认如果不实现该代理方法 视为所有请求都是同意加载的
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 获取将要加载的请求的字符串 而且前缀为回调页
        // hasPrefix前缀 hasSuffix后缀
        if let urlString = request.url?.absoluteString, urlString.hasPrefix(CZRedirect_uri){
            // 判断请求参数是否为nil
            if let query = request.url?.query {
                 print(query)
                // 截取code
                let code = query.substring(from: "code=".endIndex)
                print("结果",code)
                CZOAuthViewModel.share.loadUserAccount(code: code, isFinish: { (isFinish) in
                    if !isFinish {
                        print("请求失败")
                        return
                    }
                    print("请求成功")
                    // 关闭当前控制器
                    self.dismiss(animated: false, completion: { 
                        // 发送通知告知appdelegate 切换根控制器未欢迎界面
                        NotificationCenter.default.post(name: CZSWITCHROOTVCNOTI, object: nil)
                    })
                })
            }
        }
        return true
    }
}



